<script setup lang="ts">
import { onMounted, onUnmounted, reactive } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { LogicalSize, Window } from '@tauri-apps/api/window';
import { writeText } from '@tauri-apps/plugin-clipboard-manager';
import { useDragDrop } from '../../../hooks/drag-drop.ts';

const currentWindow = Window.getCurrent();
const state = reactive({
  isDragging: false,
  keywords: '',
  loading: false,
  resultList: [],
  windowW: 500,
  windowH: 40,
  timer: null
});
const setWindowSize = () => {
  currentWindow.setSize(new LogicalSize(state.windowW, state.windowH));
};
const searchCode = () => {
  if (state.timer) {
    clearTimeout(state.timer);
  }
  state.timer = setTimeout(() => {
    getCodeList();
  }, 300);
};

const getCodeList = () => {
  invoke('list_code_info', {
    keyword: state.keywords,
  }).then(res => {
    state.resultList = res;
    let height = state.resultList.length * 150;
    if (height >= 300) {
      height = 300;
    }
    if (height === 0) {
      height = 150;
    }
    currentWindow.setSize(new LogicalSize(500, height))
  });
};
const dblCopy = data => {
  writeText(data.code).then(res => {
    window.$message.success('复制成功');
  });
};
const { startDrag, doDrag, endDrag} = useDragDrop();
onMounted( () => {
  document.addEventListener('mousemove', doDrag);
  document.addEventListener('mouseup', endDrag);
  setWindowSize();
  getCodeList();
});
onUnmounted(() => {
  document.removeEventListener('mousemove', doDrag);
  document.removeEventListener('mouseup', endDrag);
});
</script>

<template>
  <div class="floater-container">
    <n-input class="w-100%" v-model:value="state.keywords" size="large" clearable
             @mousedown="startDrag"
             placeholder="请输入关键字搜索" @input="searchCode"></n-input>
    <n-scrollbar style="height: calc(100vh - 40px);">
      <div class="result-list" v-if="state.resultList.length > 0">
        <div class="item" v-for="(item, index) in state.resultList" :key="item.id" @dblclick="dblCopy(item)">
          <div class="title">{{index + 1}}、{{ item.title }}</div>
          <v-md-preview :text="item.code"></v-md-preview>
        </div>
      </div>
      <n-empty v-else class="mt4" description="暂无数据" />
    </n-scrollbar>
  </div>
</template>

<style scoped lang="scss">
.floater-container{
  width: 500px;
}
</style>
